﻿using MediatR;
using SC.GirdManage.Common;
using SC.GirdManage.Repository;
using SC.GridManage.API.Write.Application.Command.UnitGrid;
using SC.GridManage.Domain.Models;

namespace SC.GridManage.API.Write.Application.Handler.UnitGrid
{
    public class DelUnitGridHandler : IRequestHandler<DelUnitGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UnitGridModel> unitGridRepo;

        public DelUnitGridHandler(IBaseRepository<UnitGridModel> unitGridRepo)
        {
            this.unitGridRepo = unitGridRepo;
        }

        Task<ApiResult<int>> IRequestHandler<DelUnitGridCommand, ApiResult<int>>.Handle(DelUnitGridCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var model = unitGridRepo.GetModelAsync(request.Id).Result;
            if (model == null) {
                result.Data = 0;
                result.Msg = "单元网格不存在,不可以删除.";
                result.Code = GirdManage.Common.Enums.EnumResultCode.Error;
                return Task.FromResult(result);//校验不通过,后面代码都不在执行
            }

            model.IsDeleted = true;
            int r = unitGridRepo.UpdateAsync(model).Result;

            if (r > 0)
            {
                result.Data = r;
                result.Msg = "单元网格创建成功.";
                result.Code = GirdManage.Common.Enums.EnumResultCode.Success;
            }
            else
            {
                result.Data = r;
                result.Msg = "单元网格创建失败.";
                result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
            }
            return Task.FromResult(result);
        }
    }
}
